package dao

import (
	"errors"
	"fmt"
	"strconv"
	"user_srv/basic/config"
	__ "user_srv/basic/userproto"
	"user_srv/handler/models"
	"user_srv/pkg"
)

// UserLogin 用户登录注册一体化
func UserLogin(in *__.SmsLoginReq) (error, models.User) {
	var u models.User
	if in.Mobile == "" {
		return errors.New("手机号不能为空"), u
	}
	if !pkg.IsValidMobile(in.Mobile) {
		return errors.New("手机号格式错误"), u
	}
	u.Mobile = in.Mobile
	key := "sms" + in.Mobile
	code := config.Rdb.Get(config.Ctx, key).Val()
	if code == "" {
		return errors.New("请先发送验证码"), u
	}
	if in.Code == "" {
		return errors.New("请输入验证码"), u
	}
	if in.Code != code {
		return errors.New("验证码错误"), u
	}
	if err := config.Rdb.Del(config.Ctx, key).Err(); err != nil {
		return errors.New(fmt.Sprintf("警告: 验证码验证通过但销毁失败, key=%s, err=%v", key, err)), u
	}
	if err := u.GetUserMobile(); err != nil {
		return errors.New("查询失败"), u
	}
	if u.Id == 0 {
		password := pkg.MD5("123456")
		u.Password = password
		// 注册用户
		if err := u.UserRegister(); err != nil {
			return errors.New("注册失败"), u
		}
	} else {
		// 登录用户
		if err := u.UserLogin(); err != nil {
			return errors.New("登录失败"), u
		}
	}
	return nil, u
}

// 完善用户基本信息
func UserProfile(in *__.UserProfileReq) (error, int) {
	var u models.User
	u.Id = uint64(in.Id)
	fmt.Println(u)
	if err := u.GetUserId(); err != nil {
		return errors.New("当前用户不存在"), 0
	}
	password := pkg.MD5(in.Password)
	u.Password = password
	u.NickName = in.NickName
	u.Signature = in.Signature
	u.Sex = int8(in.Sex)
	u.Address = in.Address
	if err := u.UserProfile(); err != nil {
		return errors.New("更新失败"), 0
	}
	return nil, int(u.Id)
}

// 用户密码登录
func PasswordLogin(in *__.PasswordLoginReq) (error, uint64) {
	var u models.User
	password := pkg.MD5(in.Password)
	var err error
	u = models.User{
		Mobile:   in.Mobile,
		Password: password,
	}

	if err = u.PasswordLogin(); err != nil {
		return errors.New("登录失败，账号或密码错误"), 0
	}

	if u.Id == 0 {
		return errors.New("当前登录失败，账号或密码错误"), 0
	}
	fmt.Println(u)
	return nil, u.Id
}
func GetUserInfoList(in *__.GetUserProfileReq) (error, []*__.GetUserProfile) {
	var u models.User
	list, err := u.GetUserProfile(int(in.Page), int(in.PageSize))
	if err != nil {
		return err, nil
	}
	var List []*__.GetUserProfile
	for _, item := range list {
		List = append(List, &__.GetUserProfile{
			Id:                       int32(item.Id),
			NickName:                 item.NickName,
			Signature:                item.Signature,
			RealName:                 item.RealName,
			IdCard:                   item.IdCard,
			Sex:                      strconv.Itoa(int(item.Sex)),
			Address:                  item.Address,
			IdCardVerificationStatus: strconv.Itoa(int(item.IdCardVerificationStatus)),
		})
	}
	return nil, List
}
func GetUserDetail(in *__.GetUserDetailReq) (error, models.User) {
	var u models.User
	u = models.User{
		Id: uint64(in.Id),
	}
	if err := u.GetUserDetail(); err != nil {
		return errors.New("查询失败"), u
	}
	if u.Id == 0 {
		return errors.New("用户不存在"), u
	}
	return nil, u
}
